<?php
namespace app\store\model;
use app\common\model\Shop as ShopModel;
//use app\common\library\delivery\Dada;
use think\Session;
use think\Db;

/**
 * 门店模型
 */
class Shop extends ShopModel
{
    /**
     * 添加
     */
    public function add(array $data)
    {
        if (!isset($data['logo_image_id']) || empty($data['logo_image_id'])) {
            $this->error = '请上传门店LOGO';
            return false;
        }
		$location = getLocation($data['coordinate']);
		//达达门店参数组合
		/*$coordinate = explode(',',$data['coordinate']);
		$data_shop = [];
		$dada_shop[0] = [
			'station_name' => $data['shop_name'],
			'business' => Session::get('hema_store')['wxapp']['app_type']['value'],
			'city_name' => substr($location['city'],0,-3),
			'area_name' => $location['district'],
			'station_address' => $data['address'],
			'lng' => $coordinate[1],
			'lat' => $coordinate[0],
			'contact_name' => $data['linkman'],
			'phone' => $data['phone']
		];
		
		$res = add_shop($dada_shop);
		write_log($res,__DIR__);
		if($res){
			$data['dada_shop_no'] = $res['shop_no'];
			$data['dada_city_code'] = $res['city_code'];
		}*/
		$data['province'] = $location['province'];
		$data['city'] = $location['city'];
		$data['district'] = $location['district'];
        $data['wxapp_id'] = self::$wxapp_id;
		$data['wxapp_id'] = self::$wxapp_id;
        // 开启事务
        Db::startTrans();
        try {
            // 添加
            $this->allowField(true)->save($data);
			//生成门店二维码
			if(!$this->qrCode($this->shop_id)){
				return false;
			}
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	
	
    /**
     * 编辑
     */
    public function edit($data)
    {
        if (!isset($data['logo_image_id']) || empty($data['logo_image_id'])) {
            $this->error = '请上传门店LOGO';
            return false;
        }
		$location = getLocation($data['coordinate']);
		$data['province'] = $location['province'];
		$data['city'] = $location['city'];
		$data['district'] = $location['district'];
		// 开启事务
        Db::startTrans();
        try {
            // 添加
            $this->allowField(true)->save($data);
			//生成门店二维码
			if(!$this->qrCode($this->shop_id)){
				return false;
			}
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 删除
     */
    public function remove()
    {
		$count = $this->count();
		if($count==1){
			$this->error = '至少保留一个门店';
            return false;
		}
		// 判断是否存在店员
        if ($Count = (new Shop)->where(compact('shop_clerk_id'))->count()) {
            $this->error = '该门店下存在' . $Count . '个店员，不允许删除';
            return false;
        }
		// 开启事务
        Db::startTrans();
        try {
			//删除二维码
			if(file_exists('./assets/qrcode/shop/'.$this['shop_id'].'.png'))
			{
				unlink('./assets/qrcode/shop/'.$this['shop_id'].'.png');
			}
            $this->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	
	/**
     * 生成二维码门店
     */
	private function qrCode($shop_id)
	{
		$scene = 'shop,'.$shop_id;
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
		$data = '{"scene":"'.$scene.'"}';
		$result = http_request($url,$data);
		if(isset($result['errcode'])){
			$this->error = '生成门店小程序码错误，code：'.$result['errcode'].'，msg:'.$result['errmsg'];
			return false;
		}
		file_put_contents('assets/qrcode/shop/'.$shop_id.'.png',$result); //获取的二维码数据存储到指定的文件
		return true;
	}
}
